package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        log.info("进入测试单人订单测试");
        //Shop shop = queryWithMutex(id); //加锁来解决缓存击穿
        //Shop shop = queryWithPassThrough(id); //加逻辑过期时间来解决缓存击穿
        Result result = queryById_A(id);

        return result;
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不存在");
        }
        //更新数
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return null;
    }

    //封装逻辑过期时间
    private void saveShop2Redis(Long id, Long expireSeconds) {
        //查询数据库
        Shop shop = getById(id);
        //封装
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //存入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    //逻辑过期时间来解决缓存击穿  提前热点缓存 业务前提：热点缓存过期或发生什么异常
    private Shop queryWithPassThrough(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //先查找缓存
        String ShopCache = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在 , 如果是""是false
        if (StrUtil.isBlank(ShopCache)) {
            //不存在
            return null;
        }

        //先将json反序列化
        RedisData redisData = JSONUtil.toBean(ShopCache, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //不是在他之后
            return shop;
        }
        //重建缓存
        //获得锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean tryLock = tryLock(lockKey);
        if (tryLock) {
            //获得成功，开启独立线程
            try {
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    this.saveShop2Redis(id, 20L);
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(lockKey);
            }

        }
        //返回过期的
        return shop;
    }


    //获得锁
    private boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    //释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    //添加锁，完成互斥锁，解决缓存击穿：在某一个时间被高并发访问，或是有热点信息过期，
    // 缓存重建时间长，这段时间有大量请求穿过缓存对数据库造成负担
    private Shop queryWithMutex(Long id) {
        //先查找缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String ShopCache = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在 , 如果是""是false
        if (StrUtil.isBlank(ShopCache)) {
            //不存在
            return null;
        }
        //为""情况
        if (ShopCache != null) {

            return null;

        }
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop newShop = null;
        try {

            //不存在,添加锁
            boolean isLock = tryLock(lockKey);
            //判断获取是否成功       false:已有线程处理   true:获取锁成功
            if (!isLock) {
                //false
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //再次查询是否有缓存
            //再次检测，获取到的数据一定是新的，因为前面获取锁失败一定是有其它线程去更新缓存了
            String ShopCacheTwo = stringRedisTemplate.opsForValue().get(key);
            //判断是否存在 , 如果是""是false
            if (StrUtil.isNotBlank(ShopCacheTwo)) {
                //存在
                return JSONUtil.toBean(ShopCacheTwo, Shop.class);
            }
            //查询
            newShop = getById(id);
            //判断店铺是否存在
            if (newShop == null) {
                //写入空串，解决缓存穿透
                stringRedisTemplate.opsForValue().set(
                        RedisConstants.CACHE_SHOP_KEY + id,
                        "",
                        RedisConstants.CACHE_NULL_TTL,
                        TimeUnit.MINUTES);
                return null;
            }
            //存入缓存
            stringRedisTemplate.opsForValue().set(
                    RedisConstants.CACHE_SHOP_KEY + id,
                    JSONUtil.toJsonStr(newShop),
                    RedisConstants.CACHE_SHOP_TTL,
                    TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }

        return newShop;
    }

    //解决缓存缓存穿透：一直查询到空数据，对数据库造成负担
    private Result queryById_A(Long id) {
        //先查找缓存
        String ShopCache = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        //判断是否存在 , 如果是""是false
        if (StrUtil.isNotBlank(ShopCache)) {
            //存在
            Shop shop = JSONUtil.toBean(ShopCache, Shop.class);
            return Result.ok(shop);
        }
        //为""情况
        if (ShopCache != null) {

            return Result.fail("店铺信息不存在");

        }
        //不存在,查找店铺
        Shop newShop = getById(id);
        //判断店铺是否存在
        if (newShop == null) {
            //写入空串，解决缓存穿透
            stringRedisTemplate.opsForValue().set(
                    RedisConstants.CACHE_SHOP_KEY + id,
                    "",
                    RedisConstants.CACHE_NULL_TTL,
                    TimeUnit.MINUTES);
            return Result.fail("店铺不存在");
        }
        //存入缓存
        stringRedisTemplate.opsForValue().set(
                RedisConstants.CACHE_SHOP_KEY + id,
                JSONUtil.toJsonStr(newShop),
                RedisConstants.CACHE_SHOP_TTL,
                TimeUnit.MINUTES);
        //返回
        return Result.ok(newShop);
    }
}
